{	Problem: http://codeforces.ru/problemset/problem/108/C
	Verdict: Accepted
}
uses
                SysUtils, Math;

const
    INF = maxlongint;

var
    i, n, p, x, y, z, ans, tt, cf : longint;
    a : array[0..1010, 0..2] of int64;
    res : array[0..1010, 1..3] of longint;
                pe : array[0..1010] of boolean;

begin 
                fillchar(pe, sizeof(pe), 0);
    read(n, p);
    for i := 1 to p do begin
        read(x, y, z);
                                pe[y] := true;
        inc(a[x][0]);
        a[x][1] := y;
        a[x][2] := z;
    end;
    ans := 0;
    for i := 1 to n do
        if not pe[i] then begin
            tt := i;
            cf := INF;
            while a[tt][0] > 0 do begin
                cf := min(cf, a[tt][2]);
                tt := a[tt][1];
                                                end;
                                                if tt <> i then begin
                                                        inc(ans);
                                                        res[ans][1] := i;
                                                        res[ans][2] := tt;
                                                        res[ans][3] := cf;
                                                end;
        end;
    writeln(ans);
    for i := 1 to ans do
        writeln(res[i][1], ' ', res[i][2], ' ', res[i][3]);
end.
